package com.pingtai.dao;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

public abstract class BaseDao  {
	
	
	
	private SessionFactory sessionFactory;
	private Session session;
	
	public Session getSession(){
//		if(session==null||!session.isOpen()){
			session =  sessionFactory.getCurrentSession();
//		}
		return session;
	}
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	

	public BaseDao() {
	}

	public Object getObject(Class clazz, Serializable id) {
		session = getSession();
		return sessionFactory.getCurrentSession().get(clazz, id);
	}

	public void saveOrUpdate(Object t) {
		session = getSession();
		session.saveOrUpdate(t);
		
		flush(session);
		
	}
	
	public Object load(Class cls,Integer id){
		session = getSession();
		Object obj = session.load(cls, id);
		return obj;
	}
	
	public void evict(Object t){
		session.evict(t);
	}

	public void commit(){
		session.getTransaction().commit();
	}
	
	public Object update(Object t) {
		session = getSession();
		flush(session);
		session.update(t);
		//session.refresh(t);
		flush(session);
		return t;
	}
	
	public Object update2(Object t) {
		session = getSession();
		session.update(t);
		
		return t;
	}
	
	public Object save(Object t) {
		session = getSession();
		session.save(t);
		flush(session);
		return t;
	}
	
	
	public void flush(Session s){
		s.flush();
		session.clear();
	}
	
	public void close(){
		if(session!=null&&session.isOpen()){
			session.clear();
			session.close();
		}
	}

	public void deleteObj(Object t) throws HibernateException {
		try {
			session = getSession();
			session.delete(t);
			flush(session);
		} catch (Exception e) {
		}
	}
	
}
